import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

import '../application.dart';
import '../config.dart';

class Tools {
  static final mobileExp = RegExp(r'^1[3-9][0-9]{9}$');
  static final emailExp = RegExp(r'^[\w]+@[\w]+(\.[\w]+)+$');
  static final chineseNameExp = RegExp(r'^([\xe4-\xe9][\x80-\xbf]{2}){2,4}$');
  static final usernameExp = RegExp(r'^[a-z][0-9a-z\-_]{5,}');

  static bool isMobile(String? mobile) =>
      mobile != null && mobileExp.hasMatch(mobile);
  static bool isEmail(String? email) =>
      email != null && emailExp.hasMatch(email);
  static bool isChineseName(String? name) =>
      name != null && chineseNameExp.hasMatch(name);
  static bool isUsername(String? name) =>
      name != null && usernameExp.hasMatch(name);

  static String fixImageUrl(String? url) {
    if (url == null || url.isEmpty) return '';
    if (url.startsWith('http://') || url.startsWith('https://')) return url;
    return Config.imgHost + url;
  }

  static String? fixContentImageUrl(String? html) {
    if (html == null || html.isEmpty) return html;
    //html = html.replaceAll(RegExp(r'&emsp;'),'');
    //html = html.replaceAll(RegExp(r'\bid="[^"]+"\s*'), '');

    /*html = html.replaceAllMapped(RegExp(r'<([\w]+)\s+(?:class="([^"]+)")?'),(Match match){
        //app.log.d(match)
        if(match[1]=='br'){
            return match[0];
        }else{
            return '<'+match[1]+' class="tag_'+match[1]+(match[2].isEmpty?(' '+match[2]):'')+'" ';
        }
    });*/
    html = html.replaceAllMapped(RegExp(r'src="([^"]+)"'), (Match match) {
      //app.log.d(match);
      return 'src="${fixImageUrl(match[1])}"';
    });
    return html.replaceAll("\t", "    ");
  }

  static String formatDate(DateTime date,
      {String format = 'yyyy-MM-dd HH:mm'}) {
    var formatter = DateFormat(format);
    return formatter.format(date);
  }

  static String formatDateFromTimestamp(int? timeStamp,
      {String format = 'yyyy-MM-dd HH:mm'}) {
    if (timeStamp == null || timeStamp <= 0) return '';
    DateTime date = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
    return formatDate(date, format: format);
  }

  static String parseString(dynamic val) {
    if (val == null) return '';
    if (val is String) return val;
    return val.toString();
  }

  static int parseInt(dynamic number, {int lerant = 0}) {
    return parseNumber(number, lerant: lerant.toDouble()).toInt();
  }

  static bool parseBool(dynamic val) {
    if (val == null) return false;
    if (val is bool) return val;
    if (val is int) {
      return val != 0;
    }
    String value = val.toString().toLowerCase();
    return value == '1' || value == 'true' || value == 'on';
  }

  static double parseNumber(dynamic number, {double lerant = 0.0}) {
    if (number == null) return lerant;
    String type = number.runtimeType.toString();
    if (type == 'String') {
      var result = double.tryParse(number);
      if (result != null) {
        return result;
      }
    } else if (type == 'int') {
      return number.toDouble();
    } else if (type == 'double') {
      return number;
    }

    return lerant;
  }

  static double parseDiySize(dynamic number, {double lerant = 0}) {
    return parseNumber(number, lerant: lerant) / 2;
  }

  static Color transColor(String? hash) {
    return Color(parseColor(hash));
  }

  static int parseColor(String? hash, {int dftColor = 0xffffffff}) {
    if (hash == null || hash.length < 3) return dftColor;
    if (hash.indexOf('#') == 0) hash = hash.substring(1);

    if (hash.length == 3) {
      hash = hash[0] + hash[0] + hash[1] + hash[1] + hash[2] + hash[3];
    }

    if (hash.length == 6) {
      hash = 'FF' + hash;
    }

    if (hash.length == 8) {
      return int.tryParse(hash, radix: 16) ?? dftColor;
    }
    return dftColor;
  }

  static const greyColor = Color(0xffC8C8CD);
  static const greyLightColor = Color(0xfff8f8f8);

  static const greyBorder = BorderSide(color: greyColor, width: 0.5);

  static const imgAvatar = 'assets/graphics/avatar-default.png';
  static const imgBlank = 'assets/graphics/blank.png';
  static const imgLoading = 'assets/graphics/loading.gif';
  static const imgError = 'assets/graphics/error.png';

  static Widget avatar(String? url, {size = 55.0}) {
    return image(
      url,
      placeholder: imgAvatar,
      width: size,
      height: size,
    );
  }

  static Widget image(
    String? url, {
    String placeholder = imgBlank,
    double? width,
    double? height,
    fit = BoxFit.cover,
  }) {
    if (url == null || url.isEmpty) {
      return Image.asset(
        placeholder,
        width: width,
        height: height,
        fit: fit,
      );
    }
    return FadeInImage.assetNetwork(
      placeholder: placeholder,
      image: fixImageUrl(url),
      width: width,
      height: height,
      fit: fit,
      fadeInDuration: const Duration(milliseconds: 300),
      imageErrorBuilder: (context, obj, stack) {
        app.log.d("$obj $stack");
        return Image.asset(
          imgError,
          width: width,
          height: height,
          fit: fit,
        );
      },
    );
  }
}
